package com.syqc.monitor.ui.text

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.core.graphics.toColorInt
import androidx.core.view.isVisible
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.syqc.entity.TextCar
import com.syqc.monitor.R
import com.syqc.monitor.databinding.PopupTextCarBinding

/**
 *@author  hfjs
 *@time   2025/4/22 15:48
 *@desc
 */
class TextCarsPopup(private val context: Context, dismissPopup: () -> Unit) : PopupWindow() {
    private val binding = PopupTextCarBinding.inflate(LayoutInflater.from(context))
    private val mAdapter by lazy { TextCarAdapter(context) }

    init {
        contentView = binding.root
        isClippingEnabled = false
        isFocusable = true //popupwindow设置焦点
        setBackgroundDrawable(ColorDrawable(-0x56000000)) //设置背景
        isOutsideTouchable = false //点击外面窗口消失
        width = LinearLayout.LayoutParams.MATCH_PARENT //设置SelectPicPopupWindow弹出窗体的宽
        height = LinearLayout.LayoutParams.MATCH_PARENT //设置SelectPicPopupWindow弹出窗体的高
        binding.rvTextCar.layoutManager = LinearLayoutManager(context)
        binding.rvTextCar.adapter = mAdapter

        binding.ivClose.setOnClickListener {
            dismiss()
        }
        setOnDismissListener {
            mAdapter.submitList(null)
            dismissPopup()
        }
    }

    fun setData(data: List<TextCar>) {
        mAdapter.submitList(data.toList())
        // 强制刷新可见条目
        binding.rvTextCar.invalidate()
    }


}


private class TextCarAdapter(private val context: Context) :
    ListAdapter<TextCar, TextCarAdapter.ViewHolder>(TextCarDiffCallback()) {

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val plateText: TextView = itemView.findViewById(R.id.tvPlate)
        val tmnText: TextView = itemView.findViewById(R.id.tvTmn)
        val stateCard: CardView = itemView.findViewById(R.id.cardState)
        val stateText: TextView = itemView.findViewById(R.id.tvState)
        val waitImage: ImageView = itemView.findViewById(R.id.ivWait)
    }

    private val tmn by lazy { context.getString(R.string.desc_tmn_logo) }
    private val success by lazy { context.getString(R.string.desc_cmd_success) }
    private val wait by lazy { context.getString(R.string.desc_cmd_wait) }
    private val timeout by lazy { context.getString(R.string.desc_cmd_timeout) }
    private val offline by lazy { context.getString(R.string.desc_cmd_offline) }
    private val filure by lazy { context.getString(R.string.desc_cmd_filure) }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_text_car, parent, false)
        return ViewHolder(view)
    }


    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = getItem(position)
        holder.plateText.text = item.plate
        holder.tmnText.text = "$tmn:${item.tmnKey?:""}"
        holder.stateCard.setCardBackgroundColor(handleBgStatus(item.state).toColorInt())
        holder.stateText.setTextColor(handleTextStatus(item.state).toColorInt())
        holder.stateText.text = handleText(item.state)
        if (item.state == Status.WAITING) {
            holder.waitImage.startAnimation(
                AnimationUtils.loadAnimation(context, R.anim.anim_wait)
            )
            holder.waitImage.isVisible = true
        } else {
            holder.waitImage.clearAnimation()
            holder.waitImage.isVisible = false
        }
    }

    private fun handleText(status: Status): String {
        return when (status) {
            Status.SUCCESS -> success
            Status.WAITING -> wait
            Status.OFFLINE -> offline
            Status.FAILURE -> filure
            else -> timeout
        }
    }

    private fun handleTextStatus(status: Status): String {
        return when (status) {
            Status.SUCCESS -> "#45A20D"
            Status.WAITING -> "#D59F16"
            Status.OFFLINE -> "#797D83"
            else -> "#E13A42"
        }
    }

    private fun handleBgStatus(status: Status): String {
        return when (status) {
            Status.SUCCESS -> "#DEFFCA"
            Status.WAITING -> "#FFF9BB"
            Status.OFFLINE -> "#F2F3F5"
            else -> "#FFE1E0"
        }
    }
}

private class TextCarDiffCallback : DiffUtil.ItemCallback<TextCar>() {
    override fun areItemsTheSame(oldItem: TextCar, newItem: TextCar): Boolean {
        return oldItem.carId == newItem.carId
    }

    override fun areContentsTheSame(oldItem: TextCar, newItem: TextCar): Boolean {
        return oldItem.state == newItem.state
    }
}